<template>
  <v-autocomplete
    v-model="currentVal"
    :loading="loading"
    :items="options"
    :search-input.sync="search"
    item-text="name"
    item-value="id"
    return-object
    no-filter
    outlined
    no-data-text="请输入关键字查询"
    :label="label"
    :rules="rules"
    :filter="optionFilter"
    @change="changeHandle"
  ></v-autocomplete>
</template>

<script>
    import {mapState} from 'vuex';

    /**
     * 物料选择器
     * @author Canaan
     * @date 2019/8/13 16:07.
     */
    export default {
        name: 'MaterialSelect',
        mounted() {
            this.loadData();
        },
        components: {},
        props: {
            value: null,
            label: {
                type: String,
                default: "请选择"
            },
            rules: null
        },
        data() {
            return {
                loading: false,
                options: [],
                memoryOptions: [],
                currentVal: this.value,
                search: null
            }
        },
        computed: {
            ...mapState([
                'userContext'
            ])
        },
        methods: {
            /**
             * 添加至内存
             * @author Canaan
             * @date 2019/8/1 9:17
             */
            pushToMemory(item) {
                if (!item || !item.id) {
                    return;
                }

                this.memoryOptions = this.memoryOptions.filter((val, index) => {
                    return val.id !== item.id;
                }).slice(0, 10);   //保留前10条

                this.memoryOptions.unshift(item);
            },
            remoteMethod(query) {
                let brandId;
                if (!this.userContext.id) {
                    return; //当前用户还未加载
                } else if (this.userContext.role === 'BRAND') {
                    brandId = this.userContext.brand.id;
                } else if (this.userContext.role === 'STORE') {
                    brandId = this.userContext.store.brand.id;
                }

                if (!brandId) {
                    this.options = [];
                    return;
                }

                if (!query || query.trim() === '') {
                    this.options = this.memoryOptions;
                    return;
                }

                //先在缓存中查询
                let arrs = this.memoryOptions.filter(e => {
                    return (e.name || '').toLowerCase().indexOf((query || '').toLowerCase()) > -1
                });

                if (arrs.length !== 0) {
                    this.options = arrs;
                    return;
                }

                this.loading = true;

                this.$ajax.get("material/paging", {
                    params: {
                        searchKey: query.trim(),
                        brandId: brandId
                    }
                }).then((res) => {
                    this.loading = false;
                    if (res.code === 'ok') {
                        this.options = res.data.total > 0 ? res.data.rows : [];
                        this.options.forEach(element => {
                            this.pushToMemory(element);
                        });
                        return;
                    }
                    this.$message.error(res.msg);
                })
            },
            loadData() {
                //当前没有值
                if (!this.currentVal) {
                    return;
                }
                //如果 currentVal 有值，但 options没有值，则加载数据
                let needLoad = this.options.filter((item) => {
                    return item.id === this.currentVal;
                }).length === 0;
                if (!needLoad) {
                    return;
                }
                //正在加载中
                if (this.loading) {
                    return;
                }
                this.loading = true;

                this.$ajax.get("material/get/" + this.currentVal)
                    .then((res) => {
                        this.loading = false;
                        if (res.code === 'ok') {
                            this.pushToMemory(res.data);
                            this.options = this.memoryOptions;
                            return;
                        }
                        this.$message.error(res.msg);
                    })
            },
            optionFilter(item, queryText, itemText) {
                return item;
            },
            changeHandle(val) {
                this.options = this.memoryOptions;
                this.$emit("input", val ? val.id : null);
                this.$emit('change', val);
            }
        },
        watch: {
            search(val) {
                this.remoteMethod(val)
            },
            value(val, oldVal) {
                this.currentVal = val;
                if (val) {
                    this.loadData();
                }
            }
        },
        filters: {},
        beforeDestroy() {

        }
    }
</script>

<style scoped>

</style>
